package com.cym.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cym.config.UploadResult;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

@RequestMapping("")
@Controller
public class WebController {

	@Value("${file.storage}")
	private String storage;
	@Value("${file.host}")
	private String host;

	@ResponseBody
	@RequestMapping("")
	public String main() {
		return "欢迎使用文件管理系统";
	}

	@ResponseBody
	@RequestMapping("/upload")
	public UploadResult upload(@RequestParam("file") MultipartFile file, String name) {
		if (StrUtil.isEmpty(name)) {
			name = UUID.randomUUID().toString() + "." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
		}
		String filePath = DateUtil.format(new Date(), "yyyy/MM/dd") + "/" + name;

		File dest = new File(storage + "/" + filePath);

		if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
			dest.getParentFile().mkdirs();
		}

		try {
			// 保存文件
			file.transferTo(dest);
			UploadResult uplandResult = new UploadResult();
			uplandResult.setSuccess(true);
			uplandResult.setUrl(host + "/file/" + filePath);
			return uplandResult;

		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();

			UploadResult uplandResult = new UploadResult();
			uplandResult.setSuccess(false);
			return uplandResult;
		}
	}

	@ResponseBody
	@RequestMapping("/file/**")
	public String file(HttpServletRequest request, HttpServletResponse response, String name) throws UnsupportedEncodingException {

		// 设置文件路径
		File file = new File(storage + "/" + request.getServletPath().replace("file", ""));
		if (file.exists()) {
			response.addHeader("Content-Type", "application/octet-stream");
			if (StrUtil.isNotEmpty(name)) {
				response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8")); // 设置文件名
			}
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;

	}
}